package com.nineclock.auth.intergration.processor.impl;

import cn.hutool.core.util.StrUtil;
import com.nineclock.auth.exception.NcOAuth2Exception;
import com.nineclock.auth.intergration.entity.IntergrationAuthenticationEntity;
import com.nineclock.auth.intergration.processor.AuthenticationProcessor;
import com.nineclock.common.constant.SMSConstant;
import com.nineclock.common.entity.Result;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.system.dto.SysUserDTO;
import com.nineclock.system.feign.SysUserFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 短信认证登陆
 * @author zhangyan
 * @date 2021/4/1 20:32
 */
@Component
public class SmsAuthenticationProcessor implements AuthenticationProcessor {

    @Autowired
    private SysUserFeign sysUserFeign;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean support(IntergrationAuthenticationEntity entity) {

        if (entity != null && "sms".equals(entity.getAuthType())) {
            //entity不为空,AuthType为sms --> 手机验证码认证
            return true;
        }
        return false;
    }

    @Override
    public SysUserDTO authenticate(IntergrationAuthenticationEntity entity) {
        //获取参数
        String mobile = entity.getAuthParameter("mobile"); //手机号
        String password = entity.getAuthParameter("password"); //验证码

        //校验参数
        if (StrUtil.isEmpty(mobile) || StrUtil.isEmpty(password)) {
            throw new NcException(ResponseEnum.INVALID_PARAM_ERROR);
        }

        //调用Feign 获取手机号对应的用户信息
        Result<SysUserDTO> result = sysUserFeign.query(mobile);
        SysUserDTO userDTO = result.getData();

        if (userDTO == null) {
            throw new NcException(ResponseEnum.USER_NOT_REGISTER);
        }

        //组装并返回
       /* //todo 验证码校验
        if("1234".equals(password)) {
            //验证通过
            //passwordEncoder加密方式 对验证码进行加密,返回给UserDetailsService
            userDTO.setPassword(passwordEncoder.encode(password));
            
            return userDTO;
        }else {
            //验证不通过
            throw new NcException(ResponseEnum.CODE_IMAGE_ERROR);
        }*/

        //获取redis中的验证码
        String key = SMSConstant.SMS_LOGIN_KEY_PREFIX + mobile;

        String realCode = redisTemplate.boundValueOps(key).get();
        //校验验证码
        if (StrUtil.isNotEmpty(realCode) && realCode.equals(password)){ //验证通过
            userDTO.setPassword(passwordEncoder.encode(password)); //验证码进行匹配

            return userDTO;
        }else {
            throw new NcOAuth2Exception(ResponseEnum.CODE_IMAGE_ERROR.getMessage());
        }
    }
}
